const filters = {
  toFix(value) {
    return value.toFixed(2); // 保留两位小数
  },
  toStr(value) {
    return value.toString();
  },
  toNum(value) {
    return Number(value);
  },
  toTimeByDay(value) {
    console.log(value);
    return dateFormat(value, 'YYYY/MM/dd');
  }
};

const formatNumber = function (n) {
  n = n.toString();
  return n[1] ? n : '0' + n;
};

const getRegExp = function (pattern, flags) {
  return new RegExp(pattern, flags);
};

const regYear = getRegExp('(y+)', 'i');

const dateFormat = function (timestamp, format) {
  if (!format) {
    format = 'yyyy-MM-dd hh:mm:ss';
  }
  timestamp = parseInt(timestamp);
  const realDate = new Date(timestamp);

  function timeFormat(num) {
    return num < 10 ? '0' + num : num;
  }

  const date = [
    ['M+', timeFormat(realDate.getMonth() + 1)],
    ['d+', timeFormat(realDate.getDate())],
    ['h+', timeFormat(realDate.getHours())],
    ['m+', timeFormat(realDate.getMinutes())],
    ['s+', timeFormat(realDate.getSeconds())],
    ['q+', Math.floor((realDate.getMonth() + 3) / 3)],
    ['S+', realDate.getMilliseconds()]
  ];

  const reg1 = regYear.exec(format);
  if (reg1) {
    format = format.replace(reg1[1], (realDate.getFullYear() + '').substring(4 - reg1[1].length));
  }

  for (let i = 0; i < date.length; i++) {
    const k = date[i][0];
    const v = date[i][1];
    const reg2 = getRegExp('(' + k + ')').exec(format);
    if (reg2) {
      format = format.replace(reg2[1], reg2[1].length == 1 ? v : ('00' + v).substring(('' + v).length));
    }
  }
  return format;
};

const parse = function (fmt) {
  const fmt1 = fmt.substring(0, 19);
  const reg = getRegExp('-', 'g');
  const fmt2 = fmt1.replace(reg, '/');
  return new Date(fmt2).getTime();
};

export default {
  toFix: filters.toFix,
  toStr: filters.toStr,
  toNum: filters.toNum, // 暴露接口调用
  toTimeByDay: filters.toTimeByDay
};
